import json
import openpyxl

try:
    with open('student.json','r',encoding='utf-8') as file:
        stulist = json.load(file)
except FileNotFoundError:
    stulist = []

def save_student():
    with open('student.json','w',encoding='utf-8') as file:
        json.dump(stulist,file,ensure_ascii=False,indent=4)

def print_menu():
    print('学生基本信息管理'.center(20, '-'))
    print('insert--------添加学生信息')
    print('delete--------删除学生信息')
    print('update--------修改学生信息')
    print('show----------显示学生信息')
    print('excel---------导出excel文件')
    print('average-------计算平均分')
    print('exit--------退出')
    print('-' * 28)

def insert():
    while True:
        student_id = input('请输入学号：').strip()
        student_name = input('请输入姓名：').strip()
        student_chinese = input('请输入语文成绩:').strip()
        student_math = input('请输入数学成绩:').strip()
        student_english = input('请输入英语成绩:').strip()

        new_student = {
            'id':student_id,
            'name':student_name,
            'chinese':student_chinese,
            'math':student_math,
            'english':student_english
        }

        for student in stulist:
            if student['id'] == student_id:
                print('该学号已存在，请重新输入!')
                return

        stulist.append(new_student)
        save_student()
        print('学生信息已添加')

        choose = input('继续添加(y/n)?').lower()
        if choose == 'n':
            break


def delete():
    while True:
        student_id = input('请输入要删除的学生学号：').strip()
        global stulist
        filtered_student = []
        for student in stulist:
            if student['id'] != student_id:
                filtered_student.append(student)


        stulist = filtered_student
        save_student()
        print('已删除该学生')

        choice = input('继续删除(y/n)?').lower()
        if choice == 'n':
            break


def update():
    while True:
        student_id = input("请输入要更新的学生学号: ").strip()
        for student in stulist:
            if student['id'] == student_id:
                student_name = input("请输入新姓名（留空不更改）: ").strip() or student['name']
                student_chinese = input("请输入新语文成绩（留空不更改）: ").strip() or student['chinese']
                student_math = input("请输入新数学成绩（留空不更改）: ").strip() or student['math']
                student_english = input("请输入新英语成绩（留空不更改）: ").strip() or student['english']

                student['name'] = student_name
                student['chinese'] = student_chinese
                student['math'] = student_math
                student['english'] = student_english

                save_student()
                print('学生信息已更新！')
                break
        else:
            print('未找到该学号的学生！')

        choose = input('继续更新(y/n)?').lower()
        if choose == 'n':
            break


def show():
    if not stulist:
        print('当前没有信息！')
        return

    for student in stulist:
        print(f"学号: {student['id']}, 姓名: {student['name']}, 语文: {student['chinese']}, 数学: {student['math']}, 英语: {student['english']}")


def export_excel():
    workbook = openpyxl.Workbook()
    sheet = workbook.active
    sheet.title='学生信息'

    headers = ['学号','姓名','语文','数学','英语']
    sheet.append(headers)

    for student in stulist:
        row = [student['id'], student['name'], student['chinese'], student['math'], student['english']]
        sheet.append(row)

        excel_filename = 'student.xlsx'
        workbook.save(excel_filename)
        print(f'学生信息已经导出到{excel_filename}')


def calculate_averages():
    if not stulist:
        print('当前没有学生信息，无法计算平均分。')
        return

    chinese_scores = [float(student['chinese']) for student in stulist]
    math_scores = [float(student['math']) for student in stulist]
    english_scores = [float(student['english']) for student in stulist]

    chinese_avg = sum(chinese_scores) / len(chinese_scores)
    math_avg = sum(math_scores) / len(math_scores)
    english_avg = sum(english_scores) / len(english_scores)

    print(f"语文平均分: {chinese_avg:.2f}")
    print(f"数学平均分: {math_avg:.2f}")
    print(f"英语平均分: {english_avg:.2f}")


def main():
    while True:
        print_menu()
        choice = input('请选择操作: ').strip().lower()
        if choice == 'insert':
            insert()
        elif choice == 'delete':
            delete()
        elif choice == 'update':
            update()
        elif choice == 'show':
            show()
        elif choice == 'excel':
            export_excel()
        elif choice == 'average':
            calculate_averages()
        elif choice == 'exit':
            print("退出程序。")
            break
        else:
            print('输入错误，请重新输入。')

if __name__ == '__main__':
    main()